/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/

import React from 'react';
import {
    Form,
    Input,
    Select,
} from 'antd';
import {
    SearchOutlined
} from '@ant-design/icons';
import { searchFormProps } from '@/types/soaManage'
import CarModelTreeSelect from '@/components/CarModelTreeSelect';
export default React.forwardRef(
    (props: searchFormProps | any, ref: any) => {
        // 表单数据
        // 增加注释解决eslint Unexpected empty arrow function
        const {
            buttoms,
            emitCarSysVersion = () => undefined,
            carSysVersion = '',
            status = 0,
            setUnpublishTotal = () => {
                // 设置未发布总数
            },
            unpublishTotal = 0,
            setCarMap = () => {
                // 设置车型车系map
            },
            carMap = {},
            getTableList = () => {
                // 搜索列表
            },
            setPublishedDataSource = () => {
                // 设置已发布列表数据
            },
            dispatch,
            setLoading,
            allOptionNum = false,
            allOptionDot = false,
            loadingActive = false,
        } = props
        // 搜索表单
        const [searchForm] = Form.useForm()
        // 车型车系
        const [seriesModelList, setSeriesModelList] = React.useState<any[]>([]);
        const [seriesModeVal, setSeriesModelVal] = React.useState<any[]>([]);
        // 服务矩阵版本号列表
        const [edittionList, setEdittionList] = React.useState<any[]>([]);
        // 未发布信息  
        const [defUnpublish, setDefUnpublish] = React.useState<any>({});
        // 品牌
        const [brandName, setBrandName] = React.useState<any>(localStorage.getItem('tenantCode'));
        // 重置表单
        const resetFormValue = React.useCallback(
            () => {
                setEdittionList([])
                searchForm.resetFields()
                setSeriesModelVal([])
                emitCarSysVersion('')
            }
            , []
        )
        // 获取车型车系下的版本列表
        const getEditionList = React.useCallback(
            (smCode: any, isGetList = false, autoSet = true, value = '') => {
                // 查找车型车系下的版本ｌｉｓｔ
                if (!smCode?.length) {
                    return
                }
                setLoading(true)
                if (dispatch) {
                    dispatch({
                        type: 'serviceModel/getSocListForVersion',
                        payload: {
                            current: 1,
                            pagesize: 1000,
                            sCode: smCode[0],
                            mCode: smCode[1],
                            status: 1,
                        },
                    }).then((res: any) => {
                        setLoading(false)
                        const versions: string[] = [];
                        res?.data?.dataList?.forEach((item: any) => {
                            item?.socVersion?.forEach((item2: any) => {
                                if (!versions.includes(item2.socVersion)) {
                                    versions.push(item2.socVersion);
                                }
                            });
                        });
                        setEdittionList(versions);
                        if (autoSet) {
                            searchForm?.setFieldsValue({
                                ...searchForm?.getFieldsValue(),
                                carSysVersion: value || versions[0] || '',
                                smCode: smCode
                            })
                        }
                        setSeriesModelVal(smCode);
                        emitCarSysVersion(value || versions[0] || '')
                        if (isGetList || autoSet) {
                            getTableList(
                                1, 10,
                                smCode,
                                value || versions[0],
                                3)
                        }
                    });
                }
            }, [])
        // 选择车型车系
        const selectedModel = React.useCallback(
            // eslint-disable-next-line
            (value: any, selectVal: any, allCarModelList: any, statusParam: number = status, isGetList = false, autoSet = true) => {
                // 第一个参数soc版本号，第二个参数当前选中的车型车系数组，第三个参数未使用，第四个参数当前选中的tab下标，未使用，第五个参数是否自动查询
                if (statusParam == 2) {
                    // 未发布
                    // setEdittionList([])
                    // 设置form对象值
                    searchForm?.setFieldsValue({
                        ...searchForm?.getFieldsValue(),
                        smCode: selectVal || [],
                        carSysVersion: value,
                    })
                    setSeriesModelVal(selectVal);
                    emitCarSysVersion(value)
                    if (!selectVal || !selectVal[0] || autoSet) {
                        // getTableList()
                        // 修复从状态记录跳转到未发布页面未查询列表问题
                        getTableList(1, 10, selectVal, value, 2);
                    }
                }
                // else if (selectVal?.length && statusParam == 3) {
                //     // 已发布
                //     getEditionList(selectVal, isGetList, autoSet, value)
                // }
            }, [status, seriesModelList])
        // 获取车型个车系
        const getCarType = React.useCallback(
            async (statusParam: number = status, changeAk = false, autoSet = true) => {
                // 第一个参数当前选中的tab下标，第二个参数是否切换下标，第三个参数否自动查询列表
                let sCode: any = '';
                let mCode: any = '';
                if (changeAk) {
                    if (statusParam == 1) {
                        // 状态记录
                        return
                    }
                    // 未发布服务
                    if (statusParam == 2) {
                        // 有未发布服务的车型车系
                        // 默认选中一个未发布的车系车型
                        if (unpublishTotal) {
                            const { defUnpublishSCode = '', defUnpublishMCode = '' } = defUnpublish
                            sCode = defUnpublishSCode;
                            mCode = defUnpublishMCode;
                        }
                        if (autoSet) {
                            // getTableList(
                            //     1, 10,
                            //     [sCode, mCode],
                            //     carMap[sCode]?.models[mCode]?.socVersion,
                            //     2
                            // );
                            selectedModel(
                                sCode ? carMap[sCode]?.models[mCode]?.socVersion : '',
                                sCode ? [sCode, mCode] : [],
                                null, statusParam
                            );
                        }
                    }
                    // 已发布服务
                    if (statusParam == 3 && autoSet) {
                        // 重置数据
                        // resetFormValue()
                        // 获取车型车型
                        const defaultSelectVal = [seriesModelList[0]?.value, seriesModelList[0]?.children[0]?.value];
                        getEditionList(defaultSelectVal, false, true, '')
                    }
                } else {
                    if (dispatch) {
                        // setLoading(true)
                        if (!changeAk && autoSet) {
                            dispatch({
                                type: 'vehicleInfoQuery/getData',
                                payload: {
                                    url: '/common/vehicle/getcurrentbrand',
                                },
                                callback: (e: any) => {
                                    if (e?.data?.[0]?.brandName) {
                                        setBrandName(e?.data?.[0]?.brandName)
                                    }
                                },
                            })
                        }
                        setLoading(true);
                        dispatch({
                            type: 'serviceModel/getPublishDetail',
                        }).then((resCar: any) => {
                            setLoading(false);
                            // 切换未发布服务
                            if (resCar?.data?.unpublishTotal) {
                                // fix-eslint error Unsafe usage of optional chaining
                                const defUnpublishSCode = resCar?.data?.defUnpublish?.defUnpublishSCode || '';
                                const defUnpublishMCode = resCar?.data?.defUnpublish?.defUnpublishMCode || '';
                                sCode = defUnpublishSCode;
                                mCode = defUnpublishMCode;
                                setDefUnpublish({ defUnpublishSCode, defUnpublishMCode })
                            }
                            if (statusParam == 2) {
                                // 有未发布服务的车型车系
                                // 默认选中一个未发布的车系车型
                                if (autoSet) {
                                    selectedModel(
                                        resCar?.data?.allCarModelMap[sCode]?.models[mCode]?.socVersion,
                                        [sCode, mCode],
                                        null,
                                        statusParam,
                                        autoSet
                                    );
                                }
                            }
                            // 已发布服务
                            if (statusParam == 3 && autoSet) {
                                resetFormValue()
                            }
                            setCarMap(resCar?.data?.allCarModelMap || {});
                            setSeriesModelList(resCar?.data?.allCarModelList || []);
                            setUnpublishTotal(resCar?.data?.unpublishTotal || 0);
                        });
                    }
                }
            }, [status, defUnpublish, unpublishTotal, seriesModelList])
        React.useEffect(() => {
            getCarType()
        }, [])
        React.useImperativeHandle(ref, () => {
            return {
                getCarType,
                selectedModel,
                getEditionList,
                getTableList,
                carMap,
                searchForm,
                seriesModelList
            }
        })
        // 服务名称
        const domServicesName = React.useMemo(
            () =>
                <Form.Item
                    // label="服务名称"
                    name={'servicesName'}>
                    <Input
                        maxLength={20}
                        // style={{ width: 245 }}
                        placeholder={'请输入服务名进行筛选'}
                        allowClear
                        suffix={<SearchOutlined onClick={
                            () => getTableList()
                        } />}
                        onPressEnter={() => getTableList()}
                    />
                </Form.Item>,
            [getTableList]
        )
        // 品牌
        const domBrand = React.useMemo(
            () =>
                <Form.Item
                    label="品牌"
                    name={'brand'}>
                    <span style={{ display: 'none' }}>{brandName}</span>
                    <Input
                        value={brandName}
                        disabled
                        // style={{ width: 150 }}
                        placeholder={'请输入品牌'}
                        allowClear
                    />
                </Form.Item>,
            [brandName]
        )
        // 车型车系
        const domSeriesModeVal = React.useMemo(
            () =>
                <Form.Item
                    label="车型"
                    name={'smCode'}>
                    <CarModelTreeSelect
                        key={status}
                        // carModelList={
                        //     status == 2 ? seriesModelList?.filter((smItem: any) => {
                        //         return smItem.unpublishCount
                        //     })?.map((smItem: any) => {
                        //         return {
                        //             ...smItem,
                        //             children: smItem?.children?.filter((smcItem: any) => smcItem.showDot)
                        //         }
                        //     }) : seriesModelList
                        // }
                        carModelList={seriesModelList}
                        othProps={{
                            allowClear: false,
                            // size: 'large',
                            style: { width: '100%' }
                        }}
                        allOptionNum={allOptionNum}
                        allOptionDot={allOptionDot}
                        carVal={seriesModeVal}
                        emitSelect={
                            (selectVal: any) => {
                                // 使用父组件传过来的activeKey，避免变量值混乱
                                if (status == 3) {
                                    // 如果是已发布状态，则使用已发布的数据查询soc版本号和列表
                                    getEditionList(selectVal, false, true, '')
                                } else {
                                    selectedModel(carMap[selectVal[0]]?.models[selectVal[1]]?.socVersion, selectVal, null)
                                }
                            }
                        }
                    />
                </Form.Item>,
            [seriesModeVal, seriesModelList, allOptionNum, allOptionDot, status]
        )
        // 版本
        const domCarSysVersion = React.useMemo(
            () =>
                <Form.Item
                    label="服务矩阵版本号"
                    name={'carSysVersion'}>
                    <span style={{ display: 'none' }}>{carSysVersion}</span>
                    <Select
                        // style={{ width: 150 }}
                        disabled={!(status == 3)}
                        value={carSysVersion}
                        allowClear
                        onChange={(value) => {
                            searchForm?.setFieldsValue({
                                ...searchForm?.getFieldsValue(),
                                carSysVersion: value,
                            })
                            emitCarSysVersion(value)
                            if (!value) {
                                // 清空列表数据
                                setPublishedDataSource();
                            }
                            // getTableList()
                        }}
                        options={
                            edittionList.map((item) => {
                                return {
                                    label: item,
                                    value: item
                                }
                            })
                        }>
                    </Select>
                </Form.Item>,
            [status, carSysVersion, edittionList, setPublishedDataSource]
        )
        // 业务按钮
        const domButtoms = React.useMemo(
            () =>
                <div style={{ flexGrow: 1, textAlign: 'right', padding: '25px 0', marginRight: 0 }}>
                    {buttoms}
                </div>,
            [buttoms]
        )
        // 服务搜索表单
        const domForm = React.useMemo(
            () =>
                <div className='search-form' key={23} style={{ display: loadingActive ? 'block' : 'none' }}>
                    <Form
                        style={{
                            backgroundColor: '#fff',
                            padding: '20px',
                        }}
                        form={searchForm}
                        layout='inline'
                        initialValues={{
                            servicesName: '',
                            selectBrand: '',
                            carSysVersion: '',
                            smCode: []
                        }}>
                        {domServicesName}
                        {domBrand}
                        {domSeriesModeVal}
                        {domCarSysVersion}
                        {domButtoms}
                    </Form>
                </div>,
            [domServicesName, domSeriesModeVal, domCarSysVersion, domButtoms]
        )
        return domForm
    }
)
